/***************************************************************************
 *   Copyright (C) 2007 by Sebastian Bilski, Lance Cooper, Jeff Rebacz,
 *   									and Alex Zelenskiy
 *   sbilski@iit.edu
 *   lance.m.cooper@gmail.com
 *   jeff.rebacz@gmail.com
 *   voiceofanarchy@gmail.com
 *
 *	This file is part of connect3
 *
 *   connect3 is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License, version 2,
 *    as published by the Free Software Foundation
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc., 
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 ***************************************************************************/

/*
 * GUI_Join_A_Game.java
 *
 * Created on December 3, 2007, 10:34 AM
 */

import java.awt.Color;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jdesktop.application.Application;
import org.jdesktop.*;
import javax.swing.*;

public class GUI_Join_A_Game extends javax.swing.JFrame {
    
	private class ServerListEntry {
		public String ip = "";
		public String motd = "";
		public String port = "";
		public ServerListEntry(String ip, String motd, String port) {
			this.ip = ip;
			this.motd = motd;
			this.port = port;
		}
		public String toString()
		{
			String ret = ip + ":" + port;
			while(ret.length() < 22)
				ret += " ";
			return ret + motd;
		}
	}

	//	 Variables declaration - do not modify
    private javax.swing.JButton cancel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton joinByIP;
    private javax.swing.JButton joinSelected;
    private javax.swing.JButton updateSeverList;
    private DefaultListModel serverIp = new DefaultListModel();
    // End of variables declaration
	
    private GUI_Main_Menu parent_window;
    
    /** Creates new form GUI_Join_A_Game */
    public GUI_Join_A_Game(GUI_Main_Menu gmm) {
    	super("Connect 3 - Join a Game");
        initComponents();
        parent_window=gmm;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        joinSelected = new javax.swing.JButton();
        joinByIP = new javax.swing.JButton();
        cancel = new javax.swing.JButton();
        updateSeverList = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        
        joinSelected.setText("join selected game"); // NOI18N
        joinSelected.setName("joinSelected"); // NOI18N
        joinSelected.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                joinSelectedMouseClicked(evt);
            }
        });

        joinByIP.setText("join by IP"); // NOI18N
        joinByIP.setName("joinByIP"); // NOI18N
        joinByIP.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                joinByIPMouseClicked(evt);
            }
        });

        cancel.setText("cancel"); // NOI18N
        cancel.setName("cancel"); // NOI18N
        cancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancel(evt);
            }
        });

        updateSeverList.setText("update server list"); // NOI18N
        updateSeverList.setName("updateSeverList"); // NOI18N
        updateSeverList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                updateSeverListMouseClicked(evt);
            }
        });
        updateSeverList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateSeverListActionPerformed(evt);
            }
        });

        jLabel1.setFont(new Font("Tahoma",Font.PLAIN,36)); // NOI18N
        jLabel1.setText("Join a Game"); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(updateSeverList, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                            .addComponent(joinSelected, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                            .addComponent(joinByIP, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                            .addComponent(cancel, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE))
                        .addGap(23, 23, 23))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(jLabel1)
                .addGap(245, 245, 245)
                .addComponent(updateSeverList)
                .addGap(26, 26, 26)
                .addComponent(joinSelected)
                .addGap(31, 31, 31)
                .addComponent(joinByIP)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                .addComponent(cancel)
                .addGap(70, 70, 70))
        );

        jLabel2.setText("IP Address"); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jList1.setModel(serverIp);
        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.setName("jList1"); // NOI18N
        jScrollPane1.setViewportView(jList1);

        jLabel3.setText("MOTD"); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(""); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(""); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 569, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5)))
                .addGap(55, 55, 55)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(52, 52, 52))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(131, 131, 131)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void cancel(java.awt.event.MouseEvent evt) {
        this.setVisible(false);
        this.dispose();
        parent_window.setVisible(true);
    }

    private void updateSeverListActionPerformed(java.awt.event.ActionEvent evt) {
    	URL location = null;
    	try {
    		location = new URL("http://hackergirlsliketoparty.com/connect/printservers.php");
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return;
		}
		HttpURLConnection list = null;
    	try {
			list = (HttpURLConnection) location.openConnection();
			list.setRequestMethod("GET");
			list.setDoInput(true);
			list.setDoOutput(false);
			list.setRequestMethod("GET");
			int resp = list.getResponseCode();
			if(resp != 200)
				throw new IOException("non-successful response recieved: " + resp);
			BufferedReader content = new BufferedReader(new InputStreamReader(list.getInputStream()));
			String line;
			Pattern matchIp = Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s(.*)\\s(\\d{1,4})");
			while((line = content.readLine()) != null)
			{
				System.err.println("got server line: " + line);
				Matcher match = matchIp.matcher(line);
				if(!match.find(0))
					continue;
				String ip = match.group(1);
				String motd = match.group(2);
				String port = match.group(3);
				System.err.println("ip is " + ip + " " + motd + " " + port);
				if(ip == null || port == null || motd == null)
					continue;
				serverIp.addElement(new ServerListEntry(ip, motd, port));
			}
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this,"Could not connect to master server.","connection error", JOptionPane.DEFAULT_OPTION);
		}
		finally
    	{
    		list.disconnect();
    	}
    }

    private void joinByIPMouseClicked(java.awt.event.MouseEvent evt) {
        new GUI_Join_By_IP(this,true).setVisible(true);
    	toBack();
    }

    private void joinSelectedMouseClicked(java.awt.event.MouseEvent evt) {
    	ClientController cl = new ClientController();
    	ServerListEntry se =  (ServerListEntry) serverIp.get(jList1.getSelectedIndex());
    	if(cl.connect(se.ip, Integer.parseInt(se.port))){
    		cl.run();
    		dispose();
    	}else{
    		JOptionPane.showMessageDialog(this,"Could not connect to this ip address.","connection error", JOptionPane.DEFAULT_OPTION);
    	}
    }

    private void updateSeverListMouseClicked(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
    }
}
